import { defineStore } from "pinia"
import { post, get, put } from "@/axios/request";
import { dialog } from '@/utils/dialog'
import router from "@/router";

export const useStore = defineStore("data", {
  state: () => {
    return ({
      configTabId: 1, // 配置页面tab点击id
      token: localStorage.getItem("token") || "",
      platform: 1,
      // 注册参数
      register: {
        phone: "",
        code: "",
        password: "",
        invite_code: "",
      },

      //登录参数
      login: {
        username: "",
        password: "",
      },

      isLive: false,

      runningData: null,
      
      // 用户信息
      userInfo: {
        "phone": "",
        "username": "",
        "createdAt": "",
        "updatedAt": "",
        "avatar": "",
        "invited": "",
        "invitedBy": null,
        "licenseKey": "",
        "license_name": "",
        "level": 1,
        "id": "",
        "invitees": [],
        "invitee_count": 0
      },

      // 余额
      computeBalance: 0,

      // 用户配置信息
      userConfig: {
        "userId": "",
        "bannedType": "replace",
        "bannedlist": [
          {
            "origin": "钱",
            "target": "米"
          }
        ],
        "createdAt": "",
        "dsApiKey": "",
        "dsBaseUrl": "https://ark.cn-beijing.volces.com/api/v3",
        "dsModel": "",
        "dsSpace": 2,
        "dsUser": "",
        "dyName": "",
        "giftTxt": [],
        "giftTxtSpace": 30,
        "likeTxt": [],
        "likeTxtSpace": 60,
        "loveTxt": [],
        "loveTxtSpace": 15,
        "mainReload": false,
        "mainTxt": [],
        "mainTxtSpace": [
          0.2,
          0.3
        ],
        "musicType": false,
        "speakType": true,
        "updatedAt": "",
        "welcomeSpace": 30,
        "welcometxt": [],
        "zpApiKey": "b5e46e1eb70c46f484ca7a95f8529d8e.BYbEru0b3W71fToH",
        "zpModel": "glm-4-flash",
        "zpUser": "你是一个句子重写作家，请按以下要求改写输入句子：替换部分字词，保持原句核心意思不变，且字数与原句一致。仅进行部分字词替换，不添加额外说明、问候或结束语。改写结果须适用于语音合成，仅采用中文，不含任何英文内容。确保改写文本中不出现涉及资金、虚拟形象、无人操作,无人直播，以及优惠等描述，也避免使用极限性描述词。我提供的句子：",
        "id": "",
        "enableFollow": false,
        "enableGift": false,
        "enableLike": false,
        "enableMain": false,
        "enableSmartReply": false,
        "enableWelcome": false,
        "enableAll": false,
        "enableTime": false,
      },
      enableTimeData: {
        "enableTime": false,
        "timePrefix": '',
        "timeSuffix": '',
        "timeInterval": null,
        "timeIntervalTimer": null
      },
      // 页面状态管理
      pageStates: {
        liveViewInitialized: false, // LiveView页面是否已经初始化
        dialogReminders: {} as Record<string, boolean>, // 弹窗不再提醒状态
        progress: 0, // 云电脑开启进度
      },
      liveData: {
        current: 0,
        total: 0,
        danmu: [],
      },
      // 更改密码
      changePassword: {
        phone: "",
        old_password: "",
        new_password: ""
      },

      // 忘记密码
      forgotPassword: {
        phone: "",
        code: "",
        new_password: ""
      },
      visible: false,
      type: 'open',
      loading: false,
      options: {},


      filesMuc: [],

      muc: localStorage.getItem("muc") || "",
      history:[]
    })
  },
  actions: {

     /** 显示“开启云电脑”弹窗 */
    showOpen(options: any) {
      this.type = 'open'
      this.options = options || {}
      this.visible = true
    },
    /** 显示“成功开启/关闭云电脑”弹窗（你可复用为成功态） */
    showSuccess(options: any) {
      this.type = 'success'
      this.options = options || {}
      this.visible = true
    },
    /** 主按钮点击（内部会调用 options.onConfirm） */
    async confirm() {
      if (this.loading) return
      const cb = this.options?.onConfirm
      if (!cb) return
      try {
        this.loading = true
        await cb()
      } finally {
        this.loading = false
      }
    },
    /** 关闭弹窗 */
    close() {
      this.visible = false
      // this.loading = false
      this.options = {}
    },

    async verifySms (phone: string, scene: string, code: string) {
     try {
        const res = await post("/verify_sms", { phone, scene, code })
        console.log(res)
        dialog.alert({ iconType: 'sc', message: '验证成功'});
        return res
      } catch (error) {
        console.log(error)
        return error
      }
    },

    // 更改&忘记密码
    async changePasswordAct(phone: string, old_password: any, new_password: string, code: any) {
      let data = null
      if (code) {
        data = {
          phone,
          new_password,
          code
        }
      } else {
        data = {
          phone,
          old_password,
          new_password
        }
      }

      try {
        const res = await put("/change_password", { ...data })
        console.log(res)
        dialog.alert({ iconType: 'sc', message: '密码更改成功', showCustom: true, onConfirm: () => {router.push('/login')} });
        return res
      } catch (error) {

      }
    },

    // deepseek
    async zhipu(txt: string) {
      try {
        const res = await post("/zhipu", { txt })
        console.log(res)
        return res.response
      } catch (error) {

      }
    },

     // deepseek
    async deepseek(txt: string, name: string) {
      try {
        const res = await post("/deepseek", { txt, name})
        console.log(res)
        this.history = res.history
        this.userConfig = res
        return res
      } catch (error) {

      }
    },

    // 修改用户配置
    async updateConfig(changes: object) {
      try {
        const res = await put("/config", { ...changes })
        console.log(res)
        return res
      } catch (error) {

      }
    },

    // 获取用户配置
    async getConfig() {
      try {
        const res = await get("/config")
        console.log(res)
        this.userConfig = res
        return res
      } catch (error) {
        return error
      }
    },

    // 获取音频列表
    async listFiles(ip: string) {
      try {
        const res = await get("/listFiles", { ip })
        console.log(res)
        this.filesMuc = res.model_files
        return res
      } catch (error) {
        this.loading = false
        console.log(error)
        return error
      }
    },

    // /stopInstance
    // 关机
    async stopInstance(key: string, uhostId: string) {
      try {
        const res = await post("/stopInstance", { key, uhostId })
        console.log(res)
        this.runningData = null
        return res
      } catch (error) {
        this.loading = false
        console.log(error)
        return error
      }
    },

    // 开机
    async createInstances(key: string, deviceId: string) {
      try {
        this.loading = true
        const res = await get("/createInstances", { key, deviceId })
        console.log(res)
        this.loading = false
        this.runningData = res


        return res
      } catch (error) {
        this.loading = false
        console.log(error)
        return error
      }
    },

    // 获取用户是否开机的实例
    async runningInstance(key: string) {
      try {
        const res = await get("/runningInstance", { key })
        console.log(res)
        this.runningData = res
        return res
      } catch (error) {
        console.log(error)
        return error
      }
    },


    // 获取算力余额
    async getBalance(key: string, version: string, deviceId: string) {
      try {
        const res = await get("/get_balance", { key, version, deviceId })
        console.log(res)
        this.computeBalance = res.computeBalance
        return res
      } catch (error) {
        console.log(error)
        return error
      }
    },

    // 获取用户信息
    async getProfile() {
      try {
        const res = await get("/me")
        console.log(res)
        this.userInfo = res
        await this.getBalance(res.licenseKey, "0.0.1", res.license_name)
        return res
      } catch (error) {
        console.log(error)
        return error
      }
    },

    // 获取验证码
    async getCodeAct(phone: string, scene: string) {
      try {
        const res = await post("/send_sms", { phone, scene })
        console.log(res)
        dialog.alert({ iconType: 'sc', message: '获取验证码成功'});
        return res
      } catch (error) {
        console.log(error)
        return error
      }
    },

    async loginAct() {
      try {
        const res = await post("/login", { ...this.login })
        console.log(res)
        dialog.alert({ iconType: 'sc', message: '登录成功'}).then(() => {
          this.token = res.access_token
          localStorage.setItem("token", res.access_token)
            router.push('/')
          return res
        });
        
      } catch (error) {
        console.log(error)
        return error
      }
    },
    // 注册函数
    async registerAct() {
      try {
        const res = await post("/register", { ...this.register })
        console.log(res)
        // dialog.alert({ iconType: 'sc', message: '注册成功'});
        return res
      } catch (error) {
        console.log(error)
        return error
      }
    },

    // 设置弹窗不再提醒状态
    setDialogReminder(key: string, value: boolean) {
      this.pageStates.dialogReminders[key] = value;
    },

    // 获取弹窗不再提醒状态
    getDialogReminder(key: string): boolean {
      return this.pageStates.dialogReminders[key] || false;
    },
  }
})
